/**
 * Created by lurongchang on 2022/6/24.
 */
import { countBy } from "lodash-es";
import Vue from "vue";

Vue.mixin({
  methods: {

    /* 格式化echarts数据格式
      res:接口返回数据
      xKey:接口返回数据中x取值的key
      yKey:接口返回数据中y取值的key
      seriesKey:接口返回数据中seriesName取值的key
      ps:适用于所有echarts处理
    */
    formatEchartsData(res, xKey, yKey, seriesKey) {
      let data = res.data;
      let hasData = false,
        isEmptyData = true, //是否所有数据都为空
        seriesDataObj = {},
        xData = [],
        seriesName = [],
        xDataObj = {};
      for (let i = 0; i < data.length; i++) {
        if (data[i][yKey] && data[i][yKey] != "--") isEmptyData = false;
        xData.push(data[i][xKey]);
        seriesName.push(data[i][seriesKey]);
        if (!xDataObj[data[i][xKey]]) xDataObj[data[i][xKey]] = [];
        xDataObj[data[i][xKey]].push(data[i]);
      }
      xData = Array.from(new Set(xData));
      seriesName = Array.from(new Set(seriesName));
      for (let j = 0; j < seriesName.length; j++) {
        //遍历每个系列，添加数据或空值
        seriesDataObj[seriesName[j]] = [];
        for (let key in xDataObj) {
          //x轴遍历
          hasData = false;
          for (let k = 0; k < xDataObj[key].length; k++) {
            //每个x轴的系列遍历
            if (seriesName[j] == xDataObj[key][k][seriesKey]) {
              seriesDataObj[seriesName[j]].push(xDataObj[key][k][yKey]);
              hasData = true;
              break;
            }
          }
          if (!hasData) seriesDataObj[seriesName[j]].push("");
        }
      }
      let resultChartData = {
        xData: isEmptyData ? [] : xData,
        seriesDataObj: seriesDataObj,
      };
      return resultChartData;
    },

    /*
     * toolTip自动轮播控制器
     * instance:图表实例 dataLen 图表data数量 pos 开始轮播的位置
    **/
    autoChartToolTipAni(instance, timeStep, dataLen, pos = 0) {
      var timeTrack = null;
      //轮播函数
      var toolAniFunc = function () {
        instance.dispatchAction({
          type: "showTip",
          seriesIndex: 0,
          dataIndex: pos,
        });
        pos = (pos + 1) % dataLen;
      };
      timeTrack && clearInterval(timeTrack);
      //自动开始轮播
      toolAniFunc();
      timeTrack = setInterval(toolAniFunc, timeStep);
      //鼠标移动到实例上 停止轮播 显示当前Tooltip
      instance.on("mouseover", function (params) {
        if (timeTrack) clearInterval(timeTrack);
        //记录鼠标所在位置
        pos = params.dataIndex;
      });
      //鼠标移走 从记录的pos位置开始继续轮播
      instance.on("mouseout", function () {
        timeTrack && clearInterval(timeTrack);
        toolAniFunc();
        timeTrack = setInterval(toolAniFunc, timeStep);
      });
      //销毁定时器
      this.$once("hook:beforeDestroy", () => {
        clearInterval(timeTrack);
      });
    },
  },
});
